package edu.utexas.mapreduce;

import java.util.Calendar;

import org.apache.log4j.EnhancedPatternLayout;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;


public class Log {

	//static Logger	logger = Logger.getLogger(Log.class);
	
	static Logger getLogger(int jobID, String filename, boolean stdout) {
		
		//Enable log4j
		Logger	logger = Logger.getLogger("log_" + jobID);
		
		// Need to allow for logging with the path and filename passed in by the 
		// caller thus code the constructor to take the arguments and set the 
		// paths and unique filenames when multiple runs.
		
		// Set the message format preferences
		logger.setLevel(Level.INFO);
		
		// Set the unique destination filename for this execution
		Calendar     time     = Calendar.getInstance();
		String       tmpname  = "";
		
		tmpname  = filename;
		tmpname += "." + time.get(Calendar.YEAR);
		tmpname += "-" + time.get(Calendar.MONTH);
		tmpname += "-" + time.get(Calendar.DAY_OF_MONTH);
		tmpname += "." + time.get(Calendar.HOUR_OF_DAY);
		tmpname += "." + time.get(Calendar.MINUTE);
		tmpname += "." + time.get(Calendar.SECOND);
		tmpname += "." + time.get(Calendar.MILLISECOND);
		tmpname += ".txt";
		
		FileAppender appender = null;
		try {
			EnhancedPatternLayout layout = new EnhancedPatternLayout(logFormat());
			appender = new FileAppender(layout, tmpname, true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.addAppender(appender);

		// if standard output was selected, then also use the xml configuration
		if (stdout) {
			// configure using log4j.xml preferences. This allows for console 
			// output which mirrors what was placed in the file
			DOMConfigurator.configure("log4j.xml");
		}
		
		return logger;
	}
	
	/* Format of each log entry */
	private static String logFormat() {
		String pattern = "";
		
		//pattern += "%r ";		
		//logical clock value here
		pattern += "%d{ISO8601} ";  /* date/time at msec granularity */
		pattern += "%-5.5p ";       /* priority of log event */
		pattern += "%-70.70l ";     /* Calling method/line */
		pattern += "%-12.12t ";     /* calling thread */
		pattern += "%m %n";         /* Input message */
		return pattern;
	}
}
